<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2021-05-26
 * Time: 下午3:10:08
 * Info:
 */

namespace app\common\service\admin;

use think\facade\Db;
use think\facade\Route;
use think\Lang;

class MenuService
{

    /**
     * 管理员ID
     * @var integer
     */
    protected $adminId;

    public function __construct($adminId)
    {
        $this->adminId = $adminId;

        return $this;
    }

    /**
     * 获取后台菜单树信息
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMenuTree()
    {
        $authServer = new AuthService();

        return $this->buildMenuChild(0, $this->getMenuData(), $authServer);
    }

    /**
     * 递归获取菜单树
     *
     * @param $pid
     * @param $menuList
     * @param $authServer
     *
     * @return array
     */
    private function buildMenuChild($pid, $menuList, $authServer)
    {
        $uid      = cmf_get_admin_id();
        $treeList = [];
        foreach ($menuList as &$v) {
            $check = empty($v['href']) ? true : $authServer->check($v['href'], $uid);
            ! empty($v['href']) && $v['href'] = (string)url($v['href']);
            if ($pid == $v['pid'] && $check) {
                $node  = $v;
                $child = $this->buildMenuChild($v['id'], $menuList, $authServer);
                if ( ! empty($child)) {
                    $node['children'] = $child;
                }
                if ( ! empty($v['href']) || ! empty($child)) {
                    $treeList[] = $node;
                }
            }
        }

        return $treeList;
    }

    /**
     * 获取所有菜单数据
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function getMenuData()
    {
        $lang        = cookie(config('lang.cookie_var'));
        $langFile    = app()->getAppPath()."lang/".$lang."/admin_menu.php";
        $langDataNew = [];
        if (file_exists($langFile)) {
            $langData    = include $langFile;
            $langDataNew = $langData['auth_menu'] ?? [];
        }

        $menuData = Db::name('auth_rule')->field('id,pid,title,title_en,icon,node,type')->where("delete_time",
            0)->where("is_menu=1")->order("sort asc,id asc")->select()->toArray();
        foreach ($menuData as $key => $v) {
            $menuData[$key]['href'] = $v['node'];
            $menuData[$key]['icon'] = "layui-icon ".$v['icon'];
            if ( ! empty($langDataNew) && ! empty($v['title_en'])) {
                $menuData[$key]['title'] = $langDataNew[$v['title_en']] ?: $v['title'];
            }
        }

        return $menuData;
    }
}
